package ortho_species;

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(   
					$dir_orthologs_output
					$ortho_name1 
					$ortho_name2 
					$ortho_gene1 
					$ortho_gene2 
					$ortho_prot1 
					$ortho_prot2 
					$ortho_project
					$curr_protocol_id
					);



use strict;
use warnings;
use DBI;
use DBD::Pg;
use Carp;
our $dir_orthologs_output;
our $ortho_name1  ;
our $ortho_name2  ;
our $ortho_gene1  ;
our $ortho_gene2  ;
our $ortho_prot1  ;
our $ortho_prot2  ;
our $ortho_project;
our $curr_protocol_id  ;


BEGIN

#
#	Get parameters for entire database
#
#	These are found in the DB_PARAMETERS file in the parent directory of the running script
#
{
	use db_parameters;
	use File::Spec::Functions;
#	use Module::Util qw( :all );
	my $module_dir;
	for (@INC)
	{
		if (-e $_."/db_parameters.pm")
		{
			$module_dir = $_."/";
			last;
		}
	}
	#my (undef, $module_dir,  undef) = File::Spec->splitpath(find_installed('db_parameters'));
	my $file_name = $module_dir."ORTHO_SPECIES";
	if ($ENV{GENOME_DB_PARAM_DIR})
	{
		$file_name = $ENV{GENOME_DB_PARAM_DIR};
		$file_name =~ s/^(.*)\/?$/$1\/ORTHO_SPECIES/;
	}
	open ORTHO_SPECIES, $file_name or
	    die "Error\n\tCould not open $file_name\n$@\n$!";
	my %params;
	while (<ORTHO_SPECIES>)
	{
		chomp;
		next unless m/^(.*?)[ \t]*=[ \t]*(.*?)[ \t]*$/;
		$params{uc $1} = $2;
	}

	$ortho_name1            = $params{ORTHO_NAME1  };
	$ortho_name2            = $params{ORTHO_NAME2  };
	$ortho_gene1            = $params{ORTHO_GENE1  };
	$ortho_gene2            = $params{ORTHO_GENE2  };
	$ortho_prot1            = $params{ORTHO_PROT1  };
	$ortho_prot2            = $params{ORTHO_PROT2  };
	$ortho_project          = $params{ORTHO_PROJECT};


	$dir_orthologs_output   = $params{DIR_ORTHOLOGS_OUTPUT}; 



	#
	# set curr_protocol_id
	#
	my $dbh = DBI->connect( "dbi:Pg:dbname=$db_name;host=$db_host",
							$db_user,
							'',
							{
							  RaiseError => 1,
							  AutoCommit => 1,
							  PrintError => 1
							}
						  )
			or croak "Database connection not made: $DBI::errstr";

	# is already present?
	my $array = $dbh->selectall_arrayref(
				"SELECT protocol_id ".
					"FROM orthologs.protocols WHERE name = '$ortho_project';")
			 or croak DBI::errstr();
	if (@$array)
	{
		$curr_protocol_id = $array->[0][0];
	}
	# insert it otherwise
	else
	{
		$dbh->do("INSERT INTO orthologs.protocols(name, protocol_id) VALUES ('$ortho_project', NEXTVAL('s_protocols'));")
				 or croak DBI::errstr();
		#$dbh->commit();
		my $array = $dbh->selectall_arrayref(
					"SELECT protocol_id ".
						"FROM orthologs.protocols WHERE name = '$ortho_project';")
				 or croak DBI::errstr();
		$curr_protocol_id = $array->[0][0];
	}
	$dbh->disconnect();
	
}





return 1;
